<?php

namespace app\index\controller;

use app\data\model\ActActivity;
use app\data\model\ActArticleModel;
use app\data\model\ActOrganizer;
use app\data\model\ActSettingAgreement;
use app\data\model\ActSettingTheme;
use app\data\model\ActSettingType;
use app\index\service\LoginUserService;
use think\facade\Db;

class ActivityPage extends BaseController
{
    private  $create_session_key = 'activity_creator';

    protected function initialize()
    {
        parent::initialize();
        $this->needLogin();
    }


    /**
     * 活动规范
     * @return void
     */
    public function agreementPart()
    {
        $this->needLogin();
        if ($this->request->isGet()) {
            $this->sieteTitle = '活动须知';
            $this->hideDefaultLayout = true;
            $this->vo = ActSettingAgreement::getAgreement();
            $this->confirm = @$this->getCreateCache('agreement')['confirm'];
            $this->fetch('agreement');
        } else {
            $data = $this->_vali(['confirm.require' => '是否确认必须！']);
            if (!$data['confirm']) {
                $this->error('请先同意规范！');
            }
            $this->setCreateCache('agreement', [
                'confirm' => input('confirm')
            ]);
            $this->success('');
        }
    }

    /**
     * @name:过度也
     * @author:Sam
     * @date:2024-04-17
     * @param:[string] param [desc]
    */
    public function view(){
        $hot_id_arr = ActArticleModel::order('read_count desc')->where('cat_id', 3)->limit(0, 100)->column('id');
        shuffle($hot_id_arr);
        $use_id_arr = array_slice($hot_id_arr, 0, 4);
        $this->hot = ActArticleModel::whereIn('id', $use_id_arr)->select();

        //最新文章最新100，随机4个
        //todo 隐私文章不推荐、不展示
        $this->newest = ActArticleModel::order('id desc')->where('cat_id', 3)->limit(0, 4)->select();
        $this->vo = ActSettingAgreement::getExcessive();
        $this->fetch();
    }

    private function getCreateCache($key = null)
    {
        if ($key) {
            return session($this->create_session_key . '.' . $key,) ?: [];

        } else {
            return session($this->create_session_key);
        }
    }

    private function setCreateCache($key, $value)
    {
        session($this->create_session_key . '.' . $key, $value);
    }

    private function clearCreateCache()
    {
        session($this->create_session_key, null);
    }

    /**
     * 主题部分
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function themePart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle = '活动主题';
            $this->hideDefaultLayout = true;
            $this->themeList = ActSettingTheme::select();
            $this->selected = $this->getCreateCache('theme');
            $this->fetch('theme');
        } else {
            $data = $this->_vali(['theme.require' => '主题必须！', 'theme.array' => '选中主题必须是数组！', 'theme.length:1,2' => '最多选中两个！']);
            $theme = $data['theme'];
            $this->setCreateCache('theme', $theme);
            $this->success('');
        }
    }

    public function typePart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle = '活动类型';
            $this->hideDefaultLayout = true;
            $this->typeList = ActSettingType::select();
            $this->selected = $this->getCreateCache('type');
            $this->fetch('type');
        } else {
            $data = $this->_vali(['type.require' => '类型必须！']);
            $type = $data['type'];
            $this->setCreateCache('type', $type);
            $this->success('');
        }
    }

    public function infoPart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle = '活动信息';
            $this->hideDefaultLayout = true;
            $this->typeList = ActSettingType::select();
            $this->regionList = $this->getReginTree();
            $this->vo = $this->getCreateCache('info');
            $this->organizer = ActOrganizer::where('uid',LoginUserService::get('id'))->field('id,name')->select()->toArray();
            $this->fetch('info');
        } else {
            $data = $this->_vali([
                'logo.require' => '活动图片必须！',
                'organizer_name.require' => '主办方名称必须！',
                'name.require' => '活动名称必须！',
                'begin_time.require' => '开始时间必须！',
                'end_time.require' => '结束时间必须！',
                'region_id.require' => '活动地区必须！',
                'address_detail.require' => '活动详细地址必须！',
            ]);
            if (strtotime($data['begin_time']) > strtotime($data['end_time'])) {
                $this->error('活动开始时间不能大于结束时间！');
            }
            $this->setCreateCache('info', $data);
            $this->success('');
        }
    }

    private function getReginTree()
    {
        $region = Db::name('SystemRegion')->field('id,region_name as title,parent_id as pid')->select();
        //转化为树形结构
        return $this->array2Tree($region->toArray());

    }

    private function array2Tree($list, $pid = 0)
    {
        $tree = array();

        foreach ($list as $item) {
            if ($item['pid'] == $pid) {
                // 找到子节点
                $children = $this->array2Tree($list, $item['id']);
                // 如果有子节点，则添加到当前节点的children属性中
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                // 将当前节点添加到结果树中
                $tree[] = $item;
                // 从原始数组中移除已处理的节点，防止循环时重复处理
                unset($list[array_search($item, $list)]);
            }
        }

        return $tree;
    }

    public function contentPart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle = '活动内容';
            $this->hideDefaultLayout = true;
            $this->vo = $this->getCreateCache('content');
            $this->fetch('content');
        } else {
            $data = $this->_vali([
                'desc.require' => '活动简介必须！',
                'notice.require' => '注意事项必须！',
                'abstract.require' => '摘要必须！'
            ]);
            $this->setCreateCache('content', $data);
            $this->success('');
        }
    }

    public function guestPart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle = '活动嘉宾';
            $this->hideDefaultLayout = true;
            $this->vo = $this->getCreateCache('guest');
            $this->fetch('guest');
        } else {
            $type = input('type', 'add');
            if ($type === 'add') {
                $data = $this->_vali([
                    'profile.require' => '嘉宾头像必须！',
                    'username.require' => '嘉宾名称必须！',
                    'posit.require' => '嘉宾职位必须！',
                    'company_name.require' => '嘉宾公司必须！',
                    'user_desc.require' => '嘉宾简介必须！',
                ]);
                $guest = $this->getCreateCache('guest');
                $guest[] = $data;
                $this->setCreateCache('guest', $guest);
                $this->success('');
            }
            if ($type === 'delete') {
                $id = input('id');
                $guest = $this->getCreateCache('guest');
                unset($guest[$id]);
                $this->setCreateCache('guest', $guest);
                $this->success('');
            }
            $this->error('不支持此操作！');
        }
    }
    /**
     * @name:票价设置
     * @author:Sam
     * @date:2024-04-06
     * @param:[string] param [desc]
    */
    public function ticketPart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle = '门票设置';
            $this->hideDefaultLayout = true;
            $this->ticket = $this->getCreateCache('ticket');
            $this->fetch('ticket');
        } else {
            $data = $this->_vali([
                'desc.require'            => '門票說明必須！',
                'sale_begin.require'      => '售票開始時間必須！',
                'sale_end.require'        => '售票結束時間必須！',
                'ticket_yx_start.require' => '票券有效開始時間必須必須！',
                'ticket_yx_end.require'   => '票券有效結束時間必須必須！',
                'tickets.require'         => '門票設定不得為空'
            ]);
            $data['is_open']    = input('post.is_open',1);
            $data['is_verify']  = input('post.is_verify',0);
            $data['ticket_min'] = input('post.ticket_min',1);
            $data['ticket_max'] = input('post.ticket_max',1);
            if(!is_array($data['tickets'])) $this->error('門票格式不正確');
            if(!count($data['tickets'])) $this->error('至少需要一種門票');
            $exit_ticket  = $this->getCreateCache('ticket');
            $exit_ticket_name_arr = [];
            if($exit_ticket){
                $exit_ticket_arr = $exit_ticket['tickets'];
                $exit_ticket_name_arr = array_column($exit_ticket_arr,'name');
            }
            // 统计数组中各个name值出现的次数
            $name_counts = array_count_values(array_column($data['tickets'] , "name"));
            // 检查是否有出现次数大于1的name值
            foreach ($name_counts as $name => $count) {
                if ($count > 1) {
                    $this->error("票券名称不得重复: $name\n");
                }
            }
            foreach ($data['tickets'] as $key => $value) {
                if(!isset($value['name']) || trim($value['name']) == '')   $this->error('票名稱不得為空！');
                if(!isset($value['quantity']) || !$value['quantity']  > 0)   $this->error('票數不得為空！');
            }
            if (strtotime($data['sale_begin']) > strtotime($data['sale_end'])) {
                $this->error('售票開始時間不能大於售票結束時間！');
            }
            $this->setCreateCache('ticket', $data);
            $this->success('');
        }
    }

    /**
     * @name:票卷分组
     * @author:Sam
     * @date:2024-04-05
     * @param:[string] param [desc]
    */
    public function groupPart(){
        if ($this->request->isGet()) {
            $this->sieteTitle = '票券分组';
            $this->hideDefaultLayout = true;
            $this->tickets = $this->getCreateCache('ticket');
            $this->group   = $this->getCreateCache('group');
            $this->fetch('group');
        } else {
            $type = input('type', 'add');
            if ($type === 'add') {
                $data = $this->_vali([
                    'group_name.require'          => '票券分組名稱必須！',
                    'group_number.require'        => '票券分組數量必須！',
                    'group_ticket.require'        => '票券必須！',
                    'group_price.require'         => '票券價格必須！',
                    'group_sale_begin.require'    => '票券銷售開始時間必須！',
                    'group_sale_end.require'      => '票券銷售結束時間必須！',
                    'group_yx_start_time.require' => '票券有效開始時間必須必須！',
                    'group_yx_end_time.require'   => '票券有效結束時間必須必須！',
                ]);
                $dgroup_ticket_key = request()->post('selected_ticket_key');
                $data['group_is_open']    = input('post.group_is_open',1);
                $data['group_is_verify']  = input('post.group_is_verify',0);
                $tikcets = $this->getCreateCache('ticket');
                $tikcets_arr = $tikcets['tickets']; //票券列表
                $exit_group  = $this->getCreateCache('group');
                $total_exite_number = 0;
                if(count($exit_group)){
                    // dump($exit_group);die;
                    //已设置的票
                    foreach ($exit_group as $key => $value) {
                        if(trim($value['group_name']) == trim($data['group_name'])){
                            $this->error('该分组名称已存在');
                        }
                        if( trim($value['group_ticket']) == $data['group_ticket']){
                            //已配置改票券分组数量
                            $total_exite_number += $value['group_number'];
                        }
                    }
                }
                if($tikcets_arr[$dgroup_ticket_key-1]['quantity'] <= $data['group_number'] + $total_exite_number) {
                    $this->error('票券分組數量不得大於票券剩餘數量！');
                }
                if (strtotime($data['group_sale_begin']) > strtotime($data['group_sale_end'])) {
                    $this->error('票券分组開始時間不能大於票券分组結束時間！');
                }
                if (strtotime($data['group_yx_start_time']) > strtotime($data['group_yx_end_time'])) {
                    $this->error('票券分组有效期開始時間不能大於票券分组有效期結束時間！');
                }
                
                $group = $this->getCreateCache('group') ?? [];
                if(count($group)){
                    foreach ($group as $key => $value) {
                        if(trim($value['group_name']) == trim($data['group_name'])){
                            $this->error('该票券分组名称已存在');
                        }
                    }
                }
                $group[] = $data;
                $this->setCreateCache('group', $group);
                $this->success('操作成功');
            }
            if ($type === 'delete') {
                $ids = input('ids');
                $indexesToDelete = array_flip(explode(',', $ids));
                if(!count($indexesToDelete))  $this->error('請至少選擇一個分組');
                $group = $this->getCreateCache('group');
                $group = array_diff_key($group, $indexesToDelete);
                $this->setCreateCache('group', array_values($group));
                $this->success('操作成功');
            }
            $this->error('不支持此操作！');
        }
    }

    /**
     * @name:自定义表单
     * @author:Sam
     * @date:2024-04-07
     * @param:[string] param [desc]
    */
    public function diyformPart(){
        if ($this->request->isGet()) {
            $this->sieteTitle = '自定义表单';
            $this->hideDefaultLayout = true;
            $this->tickets = $this->getCreateCache('ticket');
            $this->group   = $this->getCreateCache('group');
            $diyform       = $this->getCreateCache('diyform');
            if(count($diyform)){
                foreach ($diyform as $key => &$value) {
                    if(isset($value['options']) && trim($value['options']) !=''){
                        $value['options_arr'] = explode('|',$value['options']);
                    }
                }
            }
            $this->diyform   = $diyform;
            // dump($this->diyform);die;
            $this->fetch('diyform');
        } else {
            $data = $this->_vali([
                'diy.require'          => '表单信息不得为空',
            ]);
            $diy_data = json_decode($data['diy'],true);
            if(!is_array($diy_data) || !count($diy_data))  $this->error('表单格式不正确');
            foreach ($diy_data as $key => $value) {
                if(!isset($value['label']) || $value['label'] == '') {
                    $this->error('部分表单标题为空！');
                }
            }
                $this->setCreateCache('diyform', $diy_data);
                $this->success('操作成功');
            }
        }
    
    /**
     * @name:进阶设置
     * @author:Sam
     * @date:2024-04-09
     * @param:[string] param [desc]
    */
    public function  advancedPart(){
        if ($this->request->isGet()) {
            $this->sieteTitle = '进阶设置';
            $this->hideDefaultLayout = true;
            $this->advanced = $this->getCreateCache('advanced');
            // dump($this->advanced);die;
            $this->fetch('advanced');
        } else {
            $data = [];
            $data['un_public'] = request()->post('un_public',0);
            $data['show_tickets'] = request()->post('show_tickets',0);
            $this->setCreateCache('advanced', $data);
            $this->success('');
        }
    }

    /**
     * @name:支付设置
     * @author:Sam
     * @date:2024-04-09
     * @param:[string] param [desc]
    */
    public function payPart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle        = '支付设置';
            $this->hideDefaultLayout = true;
            $this->pay_type          = $this->getCreateCache('pay_type');
            // dump($this->pay_type);die;
            $this->fetch('pay');
        } else {
            $data = $this->_vali([
                'pay_type.require' => '请同意支付须知！',
            ]);
            $this->setCreateCache('pay_type', $data['pay_type']);
            $this->success('');
        }
    }

    /**
     * @name:退款
     * @author:Sam
     * @date:2024-04-09
     * @param:[string] param [desc]
    */
    public function refundPart()
    {
        if ($this->request->isGet()) {
            $this->sieteTitle = '退款设置';
            $this->hideDefaultLayout = true;
            $this->refund = $this->getCreateCache('refund');
            // dump($this->refund);die;
            $this->fetch('refund');
        } else {
            $data = $this->_vali([
                'refund_type.require' => '退款方式必须！',
            ]);
            $data['self_windows'] = input('post.self_windows','');
            $data['self_contact'] = input('post.self_contact','');
            $data['self_desc']    = input('post.self_desc','');
            $this->setCreateCache('refund', $data);
            $this->success('');
        }
    }

    public function finish()
    {
        $cache = $this->getCreateCache();
        // dump($cache);die;
        $cache_type     = $this->getCreateCache('type');
        $cache_info     = $this->getCreateCache('info');
        $cache_content  = $this->getCreateCache('content');
        $cache_payType  = $this->getCreateCache('pay_type');
        $cache_guest    = $this->getCreateCache('guest');
        $cache_theme    = $this->getCreateCache('theme');
        $cache_ticket   = $this->getCreateCache('ticket');
        $cache_group    = $this->getCreateCache('group');
        $cache_advanced = $this->getCreateCache('advanced');
        $cache_diyform  = $this->getCreateCache('diyform');
        $cache_refund   = $this->getCreateCache('refund');
        if (empty($cache)) {
            $this->error('缺少活动设置！');
        }
        Db::startTrans();
        try {
            //创建活动
            $activity = new ActActivity();
            $activity->confirm_agreement = true;
            $activity->type_id           = $cache_type;
            $activity->logo              = $cache_info['logo'];
            $activity->organizer_name    = $cache_info['organizer_name'];
            $activity->name              = $cache_info['name'];
            $activity->begin_time        = $cache_info['begin_time'];
            $activity->end_time          = $cache_info['end_time'];
            $activity->begin_timestamp   = strtotime($cache_info['begin_time']);
            $activity->end_timestamp     = strtotime($cache_info['end_time']);
            $activity->region_id         = $cache_info['region_id'];
            $activity->address_detail    = $cache_info['address_detail'];
            $activity->desc              = $cache_content['desc'];
            $activity->notice            = $cache_content['notice'];
            $activity->abstract          = $cache_content['abstract'];
            $activity->pay_accept        = (isset($cache_payType) && $cache_payType !='') ? implode(',',$cache_payType) : '';
            $activity->refund_type       = $cache_refund['refund_type'];
            $activity->self_windows      = $cache_refund['self_windows'];
            $activity->self_contact      = $cache_refund['self_contact'];
            $activity->self_desc         = $cache_refund['self_desc'];
            $activity->create_user_id    = LoginUserService::get('id');
            $activity->un_public         = $cache_advanced['un_public'];
            $activity->show_tickets      = $cache_advanced['show_tickets'];
            $activity->save();
            //保存活动主题
            $activity->saveActivityTheme($cache_theme);
            //创建活动嘉宾
            $activity->saveActivityGuests($cache_guest);
            //保存活动文章
            $activity->saveActivityArticle();
            //创建活动门票
            $activity->saveActivityTicket($cache_ticket);
            //创建票券分组
            $activity->saveActivityGroup($cache_group);
            
            //创建DIY
            $activity->saveActivityDiy($cache_diyform);
            // $this->clearCreateCache();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success('操作成功');
    }

}